package com.pks.datacenter.service.api;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.pks.datacenter.config.RedisKeyConfig;
import com.pks.datacenter.entity.api.ApiField;
import com.pks.datacenter.entity.api.ApiMethod;
import com.pks.datacenter.entity.api.ApiParams;
import com.pks.datacenter.handler.RedisHandler;
import com.pks.datacenter.mapper.api.ApiFieldMapper;
import com.pks.datacenter.mapper.api.ApiMethodMapper;
import com.pks.datacenter.mapper.api.ApiParamsMapper;
import com.pks.datacenter.mapper.api.ApiPermMapper;
import com.pks.resultful.common.SRemoteResult;
import com.pks.util.SUtilQbuilder;
import com.pks.web.mybatis.service.BasicServiceImpl;

@Component("apiMethodService")
public class ApiMethodServiceImpl extends BasicServiceImpl<ApiMethod, Long, ApiMethodMapper> implements ApiMethodService {

	@Autowired
	private ApiMethodMapper apiMethodMapper;
	@Autowired
	private RedisHandler redisHandler;
	@Autowired
	private ApiFieldMapper apiFieldMapper;
	@Autowired
	private ApiParamsMapper apiParamsMapper;
	@Autowired
	private ApiPermMapper apiPermMapper;
	

	@Override
	protected ApiMethodMapper getMapper() {
		return apiMethodMapper;
	}

	@Override
	public ApiMethod findById(Long id) {
		ApiMethod apiMethod = null;
		Object obj = redisHandler.get(RedisKeyConfig.KEY_INFO_APIUSER_PREFIX + id);
		if (obj != null) {
			apiMethod = (ApiMethod) obj;
		} else {
			apiMethod = apiMethodMapper.findById(id);
			redisHandler.set(RedisKeyConfig.KEY_INFO_APIMETHOD_PREFIX + id, apiMethod , RedisKeyConfig.CACHE_TIME);
			redisHandler.set(RedisKeyConfig.KEY_INFO_METHODNAME_PREFIX + apiMethod.getMethodName(), apiMethod , RedisKeyConfig.CACHE_TIME);
		}
		return apiMethod;
	};
	
	@Override
	public ApiMethod findByMethodName(String methodName) {
		ApiMethod apiMethod = redisHandler.getApiMethodByMethodName(methodName);
		if (apiMethod == null) {
			List<ApiMethod> apiList = apiMethodMapper.find(SUtilQbuilder.initQbuilder("methodName", methodName), 0,1,null);
			if (apiList.size() > 0) {
				apiMethod = apiList.get(0);
				redisHandler.set(RedisKeyConfig.KEY_INFO_METHODNAME_PREFIX + apiMethod.getMethodName(), apiMethod , RedisKeyConfig.CACHE_TIME);
				redisHandler.set(RedisKeyConfig.KEY_INFO_APIMETHOD_PREFIX + apiMethod.getId(), apiMethod , RedisKeyConfig.CACHE_TIME);
//				public void setApiMethodByMethodName(String apiName, ApiMethod apiMethod) {
//					set(RedisKeyConfig.KEY_INFO_METHODNAME_PREFIX + apiName, apiMethod, 4 * 60 * 60);
//				}
//				redisHandler.setApiMethodByMethodName(methodName,apiMethod);
			}
		}
		return apiMethod;
	}

	@Override
	public SRemoteResult<String> insertOrModify(ApiMethod obj, String apiFieldsJson) {
		List<ApiField> apiFieldList = null;
		if (StringUtils.isNotBlank(apiFieldsJson)) {
			try {
				apiFieldList = JSON.parseObject(apiFieldsJson, new TypeReference<List<ApiField>>(){});
			} catch (Exception e) {
				return SRemoteResult.initError("查询字段参数错误");
			}
		}
		String methodName = obj.getMethodName();
		if (obj.getId() == null) {
			obj.insertBefore();
			apiMethodMapper.insert(obj);
		} else {
			ApiMethod update = apiMethodMapper.findById(obj.getId());
			if (update == null) {
				return SRemoteResult.initErrorDataNone();
			}
			methodName = update.getMethodName();
			apiMethodMapper.update(obj);
		}
		apiFieldMapper.deleteByApiId(obj.getId());
		if (apiFieldList != null && apiFieldList.size() > 0) {
			for (int i = 0; i < apiFieldList.size(); i++) {
				ApiField apiField = apiFieldList.get(i);
				apiField.insertBefore();
				apiField.setApiId(obj.getId());
				apiField.setOrders((long)(i+1));
			}
			apiFieldMapper.inserts(apiFieldList);
		}
		redisHandler.del(RedisKeyConfig.KEY_INFO_METHODNAME_PREFIX + methodName);
		redisHandler.del(RedisKeyConfig.KEY_LIST_APIFIELDS_PREFIX + obj.getId());
		redisHandler.del(RedisKeyConfig.KEY_INFO_APIMETHOD_PREFIX + obj.getId());
		return SRemoteResult.initSuccess(null);
	}

	@Override
	public SRemoteResult<String> deleteApiMethods(List<Long> ids) {
		if (ids != null && ids.size() > 0) {
			List<String> methodNames = new ArrayList<String>();
			if (ids.size() == 1) {
				ApiMethod apiMethod = apiMethodMapper.findById(ids.get(0));
				if (apiMethod != null) {
					methodNames.add(apiMethod.getMethodName());
				}
				apiMethodMapper.delete(ids.get(0));
				apiFieldMapper.deleteByApiId(ids.get(0));
				apiParamsMapper.deleteByApiId(ids.get(0));
				apiPermMapper.deleteByApiId(ids.get(0));
			} else {
				List<ApiMethod> list = apiMethodMapper.find(SUtilQbuilder.initQbuilder("ids", ids), null, null, null);
				for (ApiMethod apiMethod : list) {
					methodNames.add(apiMethod.getMethodName());
				}
				apiMethodMapper.deleteByIds(ids);
				apiFieldMapper.deleteByApiIds(ids);
				apiParamsMapper.deleteByApiIds(ids);
				apiPermMapper.deleteByApiIds(ids);
			}
			if (methodNames.size() > 0) {
				for (String methodName : methodNames) {
					redisHandler.del(RedisKeyConfig.KEY_INFO_METHODNAME_PREFIX + methodName);
				}
			}
			if (ids.size() > 0) {
				for (Long id : ids) {
					redisHandler.del(RedisKeyConfig.KEY_INFO_APIMETHOD_PREFIX + id);
				}
			}
		}
		return SRemoteResult.initSuccess(null);
	}

	@Override
	public SRemoteResult<String> insertByCopy(Long id) {
		ApiMethod apiMethod = apiMethodMapper.findById(id);
		if (apiMethod == null) {
			return SRemoteResult.initError("接口不存在");
		}
		try {
			ApiMethod insertApiMethod = new ApiMethod();
			BeanUtils.copyProperties(insertApiMethod, apiMethod);
			insertApiMethod.setId(null);
			insertApiMethod.insertBefore();
			insertApiMethod.setApiName(apiMethod.getApiName()+ "[复制]");
			insertApiMethod.setMethodName(apiMethod.getMethodName() + "1");
			apiMethodMapper.insert(insertApiMethod);
			
			Map<String, Object> qbuilder = new HashMap<String, Object>();
			qbuilder.put("apiId", id);
			List<ApiField> apiFields = apiFieldMapper.find(qbuilder, null, null, null);
			List<ApiField> insertApiFields = new ArrayList<ApiField>(); 
			for (ApiField apiField : apiFields) {
				ApiField insert = new ApiField();
				BeanUtils.copyProperties(insert, apiField);
				insert.setId(null);
				insert.insertBefore();
				insert.setApiId(insertApiMethod.getId());
				insertApiFields.add(insert);
			}
			apiFieldMapper.inserts(insertApiFields);
			List<ApiParams> apiParams = apiParamsMapper.find(qbuilder, null, null, null);
			List<ApiParams> insertApiParams = new ArrayList<ApiParams>(); 
			for (ApiParams apiParam : apiParams) {
				ApiParams insert = new ApiParams();
				BeanUtils.copyProperties(insert, apiParam);
				insert.setId(null);
				insert.insertBefore();
				insert.setApiId(insertApiMethod.getId());
				insertApiParams.add(insert);
			}
			apiParamsMapper.inserts(insertApiParams);
			return SRemoteResult.initSuccess(null);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SRemoteResult.initError("复制失败");
	}
	
	
	
}
